package com.huajiao.review.aop;



import com.huajiao.enums.ErrorCode;
import com.huajiao.exception.BusinessException;
import com.huajiao.exception.SystemException;
import com.huajiao.response.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class ApiControllerAdvice {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public BaseResponse handleBusinessException(BusinessException businessException) {
        logger.error(businessException.getMessage(), businessException);
        return BaseResponse.builder().result(false)
            .errorCode(businessException.getCode())
            .errorMsg(businessException.getMessage())
            .build();
    }

    @ExceptionHandler(SystemException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public BaseResponse handleSystemException(SystemException systemException) {
        logger.error(systemException.getMessage(), systemException);
        return BaseResponse.builder().result(false)
            .errorCode(systemException.getCode())
            .errorMsg(systemException.getMessage())
            .build();
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public BaseResponse handleRuntimeException(RuntimeException runtimeException) {
        logger.error(runtimeException.getMessage(), runtimeException);
        return BaseResponse.builder().result(false)
            .errorCode(ErrorCode.SYSTEM_EXCEPTION.getCode())
            .errorMsg("System Error")
            .build();
    }
}
